<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
    status-icon>
    <el-form-item label="商品类型" prop="categoryId">
      <el-select v-model="ruleForm.categoryId" class="m-2" placeholder="选择商品类型">
        <el-option v-for="item in category" :key="item.id" :label="item.name" :value="item.id"
          @click="getAttributeKey(item.id)" />
      </el-select>
    </el-form-item>
    <el-form-item label="商品属性标题" prop="title">
      <el-input v-model="ruleForm.title" />
    </el-form-item>
    <el-form-item label="属性选择类型" prop="type">
      <el-select v-model="ruleForm.type" class="m-2" placeholder="选择商品属性选择类型">
        <el-option v-for="item in options" :key="item.value" :label="item.key" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="属性类型选项" prop="options" v-if="ruleForm.type !== '1'">
      <el-input v-model="ruleForm.options" readonly />
    </el-form-item>
    <template v-if="ruleForm.type !== '1'">
      <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key" :label="'选项' + index"
        :prop="'选项.' + index + '.value'">
        <el-input v-model="domain.value" @input="handleInput(domain, $event)" />
        <el-button class="mt-2" @click.prevent="removeDomain(domain)">删除</el-button>
      </el-form-item>
    </template>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        添加
      </el-button>
      <el-button @click="addDomain">新建属性选项</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form><br>
  <h3>-----------------------------------------------预览----------------------------------------------</h3><br>
  <el-table :data="table.attributeKey" style="width: 100%">
    <el-table-column prop="title" label="属性名" width="180" />
    <el-table-column label="属性值">
      <template v-slot:default="{ row }">
        <el-input v-if="row.type === '1'" />
        <el-radio-group v-else-if="row.type === '2'">
          <el-radio v-for="(item, index) in row.options" :key="index" :label="item"></el-radio>
        </el-radio-group>
        <el-checkbox-group v-else-if="row.type === '3'">
          <el-checkbox v-for="(item, index) in row.options" :key="index" :label="item"></el-checkbox>
        </el-checkbox-group>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作">
      <template v-slot:default="{ row }">
        <el-button v-if="row.type !== '1'" link type="primary" size="small"
          @click.prevent="onDeleteAttributeOptions(row.id)">删除属性选项</el-button>
        <el-button link type="primary" size="small" @click.prevent="deleteRow(row.id)">移除规格
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="dialogFormVisible" title="删除规格选项">
    <el-form :model="form">
      <el-form-item label="规格选项" :label-width="formLabelWidth">
        <el-select v-model="form.index" placeholder="Please select a zone">
          <el-option v-for="item in gridData.options" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteAttrKeyOptionByIndex">
          删除
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watchEffect } from 'vue'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
import api from '@/api';

interface RuleForm {
  categoryId: string
  title: string
  type: string
  options: string
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  categoryId: '',
  title: '',
  type: '',
  options: ''
})

const rules = reactive<FormRules<RuleForm>>({
  categoryId: [
    {
      required: true,
      message: '请选择商品类型',
      trigger: 'blur'
    },
  ],
  title: [
    {
      required: true,
      message: '请输入商品属性标题',
      trigger: 'change',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择商品属性类型',
      trigger: 'blur',
    },
  ],
  options: [
    {
      required: true,
      message: '请输入商品属性选项，可输入多个，使用（英文,）分隔，至少输入两个选项',
      trigger: 'blur',
    },
  ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.shop.addAttributeKey(ruleForm)
        .then(response => {
          formEl.resetFields()
          dynamicValidateForm.domains.splice(0, dynamicValidateForm.domains.length)
          getAttributeKey(ruleForm.categoryId)
          ElNotification({
            title: 'Success',
            message: response.data.msg,
            type: 'success',
            duration: 1500
          })
        })
        .catch(error => {
          ElNotification({
            title: 'Error',
            message: error.data.msg,
            type: 'error',
            duration: 1500
          })
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dynamicValidateForm.domains.splice(0, dynamicValidateForm.domains.length)
}


const category = ref<any[]>([])

onMounted(() => {
  getCategoryList()
})

function getCategoryList() {
  api.shop.getCategoryList()
    .then(response => {
      category.value = response.data.data
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    })
}

const options = [
  {
    value: '1',
    key: '输入框'
  },
  {
    value: '2',
    key: '单选框'
  },
  {
    value: '3',
    key: '多选框'
  },
]

const dynamicValidateForm = reactive<{
  domains: DomainItem[]
}>({
  domains: [
    {
      key: 1,
      value: '',
    },
  ],
})

interface DomainItem {
  key: number
  value: string
}

const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1)
  }
}

const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    value: '',
  })
}


watchEffect(() => {
  ruleForm.options = dynamicValidateForm.domains
    .filter(domain => domain.value !== '') // 过滤空值的 domain
    .map(domain => domain.value) // 获取所有 domain 的值
    .join(',') // 以逗号分隔合并所有值
})

const handleInput = (domain: DomainItem, event: string) => {
  if (event.includes(',')) {
    domain.value = event.replace(',', '')
  }
}


const table = reactive({
  attributeKey: [
    {
      id: '',
      title: '',
      type: '',
      options: []
    }
  ]
})

function getAttributeKey(id: string) {
  api.shop.getAttributeKey({ categoryId: id })
    .then(response => {
      table.attributeKey = response.data.data.map((item: any) => {
        return {
          id: item.id,
          title: item.title,
          type: item.type,
          options: item.options.split(',')
        }
      })
    })
    .catch(error => {
      alert(error)
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    })
}

function onDeleteAttributeOptions(id: string) {
  dialogFormVisible.value = true
  form.id=id
  api.shop.getAttrKeyOptionsById(id)
    .then(response => {
      gridData.value.options = response.data.data.map((value: any, index: { toString: () => any; }) => {
        return { id: index.toString(), title: value };
      });
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    })
}

function deleteRow(id: string) {
  api.shop.deleteAttributeKeyById(id)
    .then(response => {
      getAttributeKey(ruleForm.categoryId)
      ElNotification({
        title: 'Success',
        message: response.data.msg,
        type: 'success',
        duration: 1500
      })
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    })
}

const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
  id: '',
  index: ''
})

const gridData = ref({
  options: [
    {
      id: '',
      title: ''
    }
  ]
})

function deleteAttrKeyOptionByIndex(){
api.shop.deleteAttrKeyOptionByIndex({categoryId:ruleForm.categoryId,attrKeyId:form.id,index:form.index})
.then(response => {
      getAttributeKey(ruleForm.categoryId)
      dialogFormVisible.value = false
      ElNotification({
        title: 'Success',
        message: response.data.msg,
        type: 'success',
        duration: 1500
      })
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    })
}
</script>
<style scoped>
.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}</style>